<template>
    <view class="map-page">
        <!-- H5环境地图 -->
        <!-- #ifdef H5 -->
        <view id="h5-map-container" class="h5-map-container"></view>

        <!-- H5搜索框 -->
        <view class="search-box">
            <input class="search-input" v-model="keyword" placeholder="搜索地点（如：北京天安门）" @confirm="searchLocation" />
            <view class="search-btn" @click="searchLocation">搜索</view>
        </view>

        <!-- H5我的位置按钮 -->
        <view class="location-btn" @click="backToMyLocation">
            <text class="location-icon">📍</text>
        </view>

       <!-- H5当前位置信息 -->
        <view class="location-info" v-if="currentLocationName">
            <text class="location-name">📍 {{ currentLocationName }}</text>
        </view>
        
        <!-- H5搜索结果面板 -->
        <view class="result-panel" v-if="showResultPanel && searchResults.length > 0">
            <view class="result-header">
                <view class="result-title">搜索结果 ({{ searchResults.length }})</view>
                <view class="close-result" @click="closeResultPanel">✕</view>
            </view>
            <view class="result-list">
                <view class="result-item" v-for="(item, index) in searchResults" :key="index" @click="selectLocation(item)">
                    <view class="result-name">{{ item.name }}</view>
                    <view class="result-address">{{ item.address }}</view>
                </view>
            </view>
        </view>
        <!-- #endif -->

        <!-- 小程序环境地图 -->
        <!-- #ifndef H5 -->
        <map id="map" class="map" :latitude="latitude" :longitude="longitude" :scale="scale" :markers="markers"
            :show-location="true" @markertap="onMarkerTap">
        </map>
		
        <!-- 小程序我的位置按钮 -->
        <view class="location-btn" @click="backToMyLocation">
            <text class="location-icon">📍</text>
        </view>

        <!-- 小程序当前位置信息 -->
        <view class="location-info" v-if="currentLocationName">
            <text class="location-name">📍 {{ currentLocationName }}</text>
        </view>
        
        <!-- 小程序搜索结果面板 -->
        <view class="result-panel" v-if="showResultPanel && searchResults.length > 0">
            <view class="result-header">
                <view class="result-title">搜索结果 ({{ searchResults.length }})</view>
                <view class="close-result" @click="closeResultPanel">✕</view>
            </view>
            <scroll-view class="result-list" scroll-y>
                <view class="result-item" v-for="(item, index) in searchResults" :key="index" @click="selectLocation(item)">
                    <view class="result-name">{{ item.name }}</view>
                    <view class="result-address">{{ item.address }}</view>
                </view>
            </scroll-view>
        </view>
        <!-- #endif -->

        <!-- 房源详情弹窗 -->
        <view class="house-detail-modal" v-if="showHouseDetail">
            <view class="modal-mask" @click="closeHouseDetail"></view>
            <view class="modal-content">
                <view class="modal-header">
                    <view class="modal-title">{{ selectedArea.label }} - 房源详情</view>
                    <view class="modal-close" @click="closeHouseDetail">✕</view>
                </view>
                <scroll-view class="modal-body" scroll-y>
                    <view class="house-list">
                        <view class="house-item" v-for="(house, index) in currentHouses" :key="index">
                            <image class="house-image" :src="house.img || '/static/house-default.jpg'" mode="aspectFill"></image>
                            <view class="house-info">
                                <view class="house-title">{{ house.title }}</view>
                                <view class="house-desc">{{ house.desc }}</view>
                                <view class="house-tags">
                                    <text class="tag" v-for="(tag, tagIndex) in house.tags" :key="tagIndex">{{ tag }}</text>
                                </view>
                                <view class="house-price">
                                    <text class="price">{{ house.price }}</text>
                                    <text class="unit">元/月</text>
                                </view>
                            </view>
                        </view>
                    </view>
                    <!-- 加载更多 -->
                    <view class="load-more" v-if="hasMoreHouses">
                        <view class="load-more-btn" @click="loadMoreHouses">
                            <text>加载更多房源</text>
                            <text class="load-icon">↓</text>
                        </view>
                    </view>
                    <view class="no-more" v-else>
                        <text>没有更多房源了</text>
                    </view>
                </scroll-view>
            </view>
        </view>

        <!-- 城市切换按钮 -->
        <view class="city-selector">
            <view class="city-btn" @click="showCitySelector = true">
                <text class="city-name">{{ currentCity }}</text>
                <text class="city-arrow">▼</text>
            </view>
        </view>

        <!-- 城市选择器 -->
        <view class="city-selector-modal" v-if="showCitySelector">
            <view class="city-modal-mask" @click="showCitySelector = false"></view>
            <view class="city-modal-content">
                <view class="city-modal-header">
                    <view class="city-modal-title">选择城市</view>
                    <view class="city-modal-close" @click="showCitySelector = false">✕</view>
                </view>
                <scroll-view class="city-modal-body" scroll-y>
                    <view class="city-list">
                        <view class="city-item" 
                            v-for="city in availableCities" 
                            :key="city.value"
                            :class="{ active: currentCity === city.label }"
                            @click="selectCity(city)">
                            <text class="city-item-name">{{ city.label }}</text>
                            <text class="city-item-check" v-if="currentCity === city.label">✓</text>
                        </view>
                    </view>
                </scroll-view>
            </view>
        </view>

        <!-- 加载状态 -->
        <view class="loading-overlay" v-if="loading">
            <view class="loading-content">
                <view class="loading-spinner"></view>
                <text class="loading-text">{{ loadingText }}</text>
            </view>
        </view>
    </view>
</template>

<script>
export default {
    data() {
        return {
            latitude: 0,
            longitude: 0,
            scale: 12,
            markers: [],
            keyword: '',
            myLatitude: 0,
            myLongitude: 0,
            searchResults: [],
            currentLocationName: '',
            locationLoaded: false,
            // 百度地图API密钥
            baiduAK: '0N59ip2OHZCo2YiWF0DoynH6HbQbCwrC',
            // H5地图实例
            h5Map: null,
            h5MapLoaded: false,
            // 房源数据
            houseData: [],
            h5Overlays: [],
            showResultPanel: false,
            currentCity: '北京',
            // 城市坐标映射（主要城市）
            cityCoordinates: {
                '北京': { lat: 39.915, lng: 116.404 },
                '上海': { lat: 31.2304, lng: 121.4737 },
                '广州': { lat: 23.1291, lng: 113.2644 },
                '深圳': { lat: 22.5431, lng: 114.0579 },
                '杭州': { lat: 30.2741, lng: 120.1551 },
                '成都': { lat: 30.5728, lng: 104.0668 },
                '武汉': { lat: 30.5928, lng: 114.3055 },
                '南京': { lat: 32.0603, lng: 118.7969 },
                '天津': { lat: 39.0842, lng: 117.201 },
                '重庆': { lat: 29.563, lng: 106.5516 },
                '西安': { lat: 34.3416, lng: 108.9398 },
                '苏州': { lat: 31.2989, lng: 120.5853 },
                '长沙': { lat: 28.2282, lng: 112.9388 },
                '郑州': { lat: 34.7466, lng: 113.6253 },
                '青岛': { lat: 36.0671, lng: 120.3826 },
                '宁波': { lat: 29.8683, lng: 121.544 },
                '大连': { lat: 38.914, lng: 121.6147 }
            },
            // 新增数据：房源详情相关
            showHouseDetail: false,
            selectedArea: null,
            currentHouses: [],
            currentPage: 1,
            pageSize: 10,
            hasMoreHouses: false,
            // 模拟房源数据存储
            allHousesData: {},
            // 城市选择相关
            showCitySelector: false,
            availableCities: [], // 初始为空，从接口获取
            // 加载状态
            loading: false,
            loadingText: '加载中...'
        }
    },
    onLoad() {
        uni.showLoading({
            title: '正在获取位置...',
            mask: true
        });

        const savedCity = uni.getStorageSync('selectedCity');
        if (savedCity) {
            this.currentCity = savedCity;
        }

        uni.$on('selectCity', this.handleCityChange);

        // 先获取城市列表，然后初始化地图和房源数据
        this.getCityList().then(() => {
            // #ifdef H5
            this.loadBaiduMapScript().then(() => {
                this.getMyLocation();
                this.getHouseData();
            }).catch(() => {
                uni.hideLoading();
                uni.showToast({
                    title: '地图加载失败',
                    icon: 'none'
                });
            });
            // #endif

            // #ifndef H5
            this.getMyLocation();
            this.getHouseData();
            // #endif
        }).catch(() => {
            uni.hideLoading();
            uni.showToast({
                title: '获取城市列表失败',
                icon: 'none'
            });
        });
    },
    onUnload() {
        uni.$off('selectCity', this.handleCityChange);
        
        // #ifdef H5
        if (this.h5Map) {
            this.h5Map = null;
        }
        // #endif
    },
    methods: {
        // 获取城市列表
        async getCityList() {
            try {
                this.loading = true;
                this.loadingText = '正在获取城市列表...';

                const res = await uni.request({
                    url: 'http://localhost:8080/area/city?level=1',
                    method: 'GET'
                });

                console.log('城市列表接口返回:', res);

                if (res.statusCode === 200) {
                    const data = res.data;
                    if (data.status === 200 && data.body && Array.isArray(data.body)) {
                        this.availableCities = data.body;
                        console.log('获取到的城市列表:', this.availableCities);
                        
                        // 检查当前城市是否在列表中，如果不在则使用第一个城市
                        const currentCityExists = this.availableCities.some(city => city.label === this.currentCity);
                        if (!currentCityExists && this.availableCities.length > 0) {
                            this.currentCity = this.availableCities[0].label;
                        }
                        
                        this.loading = false;
                        return true;
                    } else {
                        throw new Error('城市数据格式错误');
                    }
                } else {
                    throw new Error(`请求失败，状态码: ${res.statusCode}`);
                }
            } catch (error) {
                console.error('获取城市列表失败:', error);
                this.loading = false;
                
                // 使用默认城市列表作为备用
                this.availableCities = [
                    { label: '北京', value: 'AREA|88cff55c-aaa4-e2e0' },
                    { label: '上海', value: 'AREA|dbf46d32-7e76-1196' },
                    { label: '广州', value: 'AREA|e4940177-c04c-383d' },
                    { label: '深圳', value: 'AREA|a6649a11-be98-b150' },
                    { label: '杭州', value: 'AREA|19b39d4f-8a36-d6f8' },
                    { label: '成都', value: 'AREA|27a05931-1701-4e74' },
                    { label: '武汉', value: 'AREA|27e414ce-a7e1-fd99' },
                    { label: '南京', value: 'AREA|93dec481-bd0b-577e' }
                ];
                
                uni.showToast({
                    title: '使用默认城市列表',
                    icon: 'none'
                });
                
                return true;
            }
        },

        // 处理城市切换事件
        handleCityChange(city) {
            if (!city) return;
            
            let newCityName = '';
            if (typeof city === 'object') {
                newCityName = city.label || city.name || city;
            } else {
                newCityName = city;
            }
            
            if (newCityName && newCityName !== this.currentCity) {
                this.currentCity = newCityName;
                console.log('地图页面更新城市:', this.currentCity);
                this.relocateToCity();
            }
        },

        // 根据城市重新定位
        relocateToCity() {
            const cityCoord = this.cityCoordinates[this.currentCity];
            if (cityCoord) {
                this.latitude = cityCoord.lat;
                this.longitude = cityCoord.lng;
                this.myLatitude = cityCoord.lat;
                this.myLongitude = cityCoord.lng;
                this.scale = 12;
                this.currentLocationName = this.currentCity;

                // #ifdef H5
                if (this.h5Map && window.BMapGL) {
                    const BMapGL = window.BMapGL;
                    const point = new BMapGL.Point(cityCoord.lng, cityCoord.lat);
                    
                    this.h5Map.clearOverlays();
                    this.h5Map.centerAndZoom(point, this.scale);
                    
                    const marker = new BMapGL.Marker(point);
                    this.h5Map.addOverlay(marker);

                    const infoWindow = new BMapGL.InfoWindow(this.currentCity, {
                        width: 200,
                        height: 50
                    });
                    marker.addEventListener('click', () => {
                        this.h5Map.openInfoWindow(infoWindow, point);
                    });
                } else {
                    this.$nextTick(() => {
                        this.initH5Map(cityCoord.lat, cityCoord.lng);
                    });
                }
                // #endif

                // #ifndef H5
                this.addMarker(cityCoord.lat, cityCoord.lng, this.currentCity);
                // #endif

                // 重新获取房源数据
                this.getHouseData();

                uni.showToast({
                    title: `已定位到${this.currentCity}`,
                    icon: 'success',
                    duration: 1500
                });
            } else {
                // 如果城市坐标不存在，使用默认坐标
                this.useDefaultLocation();
            }
        },

        // 选择城市
        selectCity(city) {
            this.currentCity = city.label;
            this.showCitySelector = false;
            
            // 保存到本地存储
            uni.setStorageSync('selectedCity', this.currentCity);
            
            // 重新定位和获取数据
            this.relocateToCity();
        },

        // 加载百度地图API脚本（H5专用）
        loadBaiduMapScript() {
            return new Promise((resolve, reject) => {
                // #ifdef H5
                if (window.BMapGL) {
                    resolve();
                    return;
                }

                const script = document.createElement('script');
                script.type = 'text/javascript';
                script.src = `https://api.map.baidu.com/api?v=1.0&type=webgl&ak=${this.baiduAK}&callback=onBMapCallback`;
                script.onerror = (err) => {
                    console.error('百度地图API加载失败:', err);
                    reject(err);
                };

                window.onBMapCallback = () => {
                    console.log('百度地图API加载成功');
                    this.h5MapLoaded = true;
                    resolve();
                };

                document.head.appendChild(script);
                // #endif

                // #ifndef H5
                resolve();
                // #endif
            });
        },

        // 初始化H5地图
        initH5Map(lat, lng) {
            // #ifdef H5
            if (!window.BMapGL) {
                console.error('百度地图API未加载');
                return;
            }

            const BMapGL = window.BMapGL;
            this.h5Map = new BMapGL.Map('h5-map-container');
            const point = new BMapGL.Point(lng, lat);

            this.h5Map.centerAndZoom(point, this.scale);
            this.h5Map.enableScrollWheelZoom(true);
            this.h5Map.addControl(new BMapGL.NavigationControl());
            this.h5Map.addControl(new BMapGL.ScaleControl());

            const marker = new BMapGL.Marker(point);
            this.h5Map.addOverlay(marker);

            const infoWindow = new BMapGL.InfoWindow(this.currentLocationName || '我的位置', {
                width: 200,
                height: 50
            });
            marker.addEventListener('click', () => {
                this.h5Map.openInfoWindow(infoWindow, point);
            });

            console.log('H5地图初始化成功', { lat, lng });

            setTimeout(() => {
                this.showHouseMarkers();
            }, 500);
            // #endif
        },

        // 获取我的位置
        getMyLocation() {
            const cityCoord = this.cityCoordinates[this.currentCity];
            if (cityCoord) {
                this.latitude = cityCoord.lat;
                this.longitude = cityCoord.lng;
                this.myLatitude = cityCoord.lat;
                this.myLongitude = cityCoord.lng;
                this.currentLocationName = this.currentCity;
                this.locationLoaded = true;

                // #ifdef H5
                this.$nextTick(() => {
                    this.initH5Map(cityCoord.lat, cityCoord.lng);
                });
                // #endif

                // #ifndef H5
                this.addMarker(cityCoord.lat, cityCoord.lng, this.currentCity);
                // #endif

                uni.hideLoading();
                return;
            }

            // #ifdef H5
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(
                    (position) => {
                        console.log('H5获取位置成功:', position);
                        this.convertToBaidu(position.coords.latitude, position.coords.longitude);
                        uni.hideLoading();
                        this.locationLoaded = true;
                    },
                    (error) => {
                        console.error('H5获取位置失败:', error);
                        uni.hideLoading();
                        this.useDefaultLocation();
                    },
                    {
                        enableHighAccuracy: true,
                        timeout: 10000,
                        maximumAge: 0
                    }
                );
            } else {
                console.log('浏览器不支持定位');
                uni.hideLoading();
                this.useDefaultLocation();
            }
            // #endif

            // #ifndef H5
            uni.getSetting({
                success: (res) => {
                    if (res.authSetting['scope.userLocation']) {
                        this._getLocationInMiniProgram();
                    } else if (res.authSetting['scope.userLocation'] === undefined) {
                        this._requestLocationPermission();
                    } else {
                        uni.hideLoading();
                        this.useDefaultLocation();
                    }
                },
                fail: () => {
                    uni.hideLoading();
                    this.useDefaultLocation();
                }
            });
            // #endif
        },
        
        // 小程序环境请求位置权限
        _requestLocationPermission() {
            uni.authorize({
                scope: 'scope.userLocation',
                success: () => {
                    this._getLocationInMiniProgram();
                },
                fail: () => {
                    uni.hideLoading();
                    this.useDefaultLocation();
                }
            });
        },
        
        // 小程序环境获取位置
        _getLocationInMiniProgram() {
            uni.getLocation({
                type: 'gcj02',
                altitude: true,
                isHighAccuracy: true,
                success: (res) => {
                    console.log('获取位置成功:', res);
                    this.convertToBaidu(res.latitude, res.longitude);
                    uni.hideLoading();
                    this.locationLoaded = true;
                },
                fail: (err) => {
                    console.error('获取位置失败:', err);
                    uni.hideLoading();
                    this.useDefaultLocation();
                }
            });
        },

        // 使用默认位置
        useDefaultLocation() {
            console.log('使用默认位置：北京');
            this.latitude = 39.915;
            this.longitude = 116.404;
            this.myLatitude = 39.915;
            this.myLongitude = 116.404;
            this.locationLoaded = true;
            this.currentLocationName = '北京市';

            // #ifdef H5
            this.$nextTick(() => {
                this.initH5Map(39.915, 116.404);
            });
            // #endif

            // #ifndef H5
            this.addMarker(39.915, 116.404, '默认位置');
            // #endif
        },

        // 坐标转换（WGS84转百度坐标）
        convertToBaidu(lat, lng) {
            this.latitude = lat;
            this.longitude = lng;
            this.myLatitude = lat;
            this.myLongitude = lng;

            // #ifdef H5
            this.$nextTick(() => {
                this.initH5Map(lat, lng);
            });
            // #endif

            // #ifndef H5
            this.addMarker(lat, lng, '我的位置');
            setTimeout(() => {
                this.showHouseMarkers();
            }, 800);
            // #endif

            this.getLocationName(lat, lng);
        },

        // 根据坐标获取位置名称（逆地理编码）
        getLocationName(lat, lng) {
            this.currentLocationName = '当前位置';

            // #ifndef H5
            uni.request({
                url: 'https://api.map.baidu.com/reverse_geocoding/v3/',
                data: {
                    ak: this.baiduAK,
                    output: 'json',
                    coordtype: 'gcj02ll',
                    location: `${lat},${lng}`
                },
                success: (res) => {
                    if (res.data.status === 0 && res.data.result) {
                        this.currentLocationName = res.data.result.formatted_address || res.data.result.sematic_description || '当前位置';
                        console.log('当前位置:', this.currentLocationName);
                    }
                },
                fail: (error) => {
                    console.log('逆地理编码请求失败，使用默认名称');
                }
            });
            // #endif
        },

        // 添加标记
        addMarker(lat, lng, title) {
            this.markers = [{
                id: Date.now(),
                latitude: lat,
                longitude: lng,
                iconPath: '/static/location.png',
                width: 30,
                height: 30,
                title: title,
                callout: {
                    content: title,
                    color: '#333',
                    fontSize: 12,
                    borderRadius: 5,
                    bgColor: '#fff',
                    padding: 5,
                    display: 'ALWAYS'
                }
            }];
        },

        // 返回我的位置
        backToMyLocation() {
            if (this.myLatitude && this.myLongitude) {
                this.latitude = this.myLatitude;
                this.longitude = this.myLongitude;
                this.scale = 15;
            } else {
                this.getMyLocation();
            }
        },

        // 搜索位置（使用百度地图地点检索API）
        searchLocation() {
            if (!this.keyword.trim()) {
                uni.showToast({
                    title: '请输入搜索关键词',
                    icon: 'none'
                });
                return;
            }

            uni.showLoading({ title: '搜索中...' });

            // #ifndef H5
            uni.request({
                url: 'https://api.map.baidu.com/place/v2/search',
                data: {
                    query: this.keyword,
                    region: '全国',
                    output: 'json',
                    ak: this.baiduAK,
                    page_size: 10
                },
                success: (res) => {
                    uni.hideLoading();
                    if (res.data.status === 0 && res.data.results && res.data.results.length > 0) {
                        this.searchResults = res.data.results;
                        this.showResultPanel = true;
                        console.log('搜索结果:', this.searchResults);
                    } else {
                        console.log('搜索返回状态:', res.data.status, '消息:', res.data.message || '未找到结果');
                        uni.showToast({
                            title: '未找到相关地点',
                            icon: 'none'
                        });
                    }
                },
                fail: (error) => {
                    uni.hideLoading();
                    console.log('搜索请求失败:', error);
                    uni.showToast({
                        title: '搜索功能暂时不可用',
                        icon: 'none'
                    });
                }
            });
            // #endif
        },
        
        // 关闭搜索结果面板
        closeResultPanel() {
            this.showResultPanel = false;
            this.searchResults = [];
        },

        // 选择搜索结果中的位置
        selectLocation(item) {
            this.latitude = item.location.lat;
            this.longitude = item.location.lng;
            this.scale = 15;
            this.currentLocationName = item.name;

            // #ifdef H5
            if (this.h5Map && window.BMapGL) {
                const BMapGL = window.BMapGL;
                const point = new BMapGL.Point(item.location.lng, item.location.lat);

                this.h5Map.clearOverlays();
                const marker = new BMapGL.Marker(point);
                this.h5Map.addOverlay(marker);
                this.h5Map.panTo(point);

                const infoWindow = new BMapGL.InfoWindow(item.name, {
                    width: 200,
                    height: 50
                });
                marker.addEventListener('click', () => {
                    this.h5Map.openInfoWindow(infoWindow, point);
                });

                setTimeout(() => {
                    this.h5Map.openInfoWindow(infoWindow, point);
                }, 300);
            }
            // #endif

            // #ifndef H5
            this.addMarker(item.location.lat, item.location.lng, item.name);
            // #endif

            this.showResultPanel = false;
            this.searchResults = [];

            uni.showToast({
                title: '已定位到' + item.name,
                icon: 'success',
                duration: 2000
            });
        },

        // 点击标记
        onMarkerTap(e) {
            console.log('点击标记:', e);
            // 处理房源标记点击
            if (e.markerId >= 1000) {
                const index = e.markerId - 1000;
                const areaData = this.houseData[index];
                if (areaData) {
                    this.showAreaHouseDetail(areaData);
                }
            }
        },

        // 获取房源数据
        async getHouseData() {
            try {
                // 显示加载状态
                this.loading = true;
                this.loadingText = `正在获取${this.currentCity}房源数据...`;

                // 根据当前城市获取对应的区域ID
                const selectedCity = this.availableCities.find(city => city.label === this.currentCity);
                if (!selectedCity) {
                    throw new Error(`未找到城市 ${this.currentCity} 的区域ID`);
                }
                
                const areaId = selectedCity.value;
                const url = `http://localhost:8080/area/map?id=${encodeURIComponent(areaId)}`;
                
                console.log(`获取${this.currentCity}的房源数据，区域ID:`, areaId, 'URL:', url);
                
                const res = await uni.request({
                    url: url,
                    method: 'GET'
                });

                console.log(`${this.currentCity}房源数据接口返回:`, res);

                if (res.statusCode === 200) {
                    const data = res.data;
                    console.log('接口返回的完整数据:', data);
                    
                    // 处理不同格式的响应数据
                    let houseData = [];
                    if (data.status === 200 && data.body) {
                        houseData = data.body;
                    } else if (Array.isArray(data)) {
                        houseData = data;
                    } else if (data.data) {
                        houseData = data.data;
                    }
                    
                    this.houseData = houseData;
                    console.log(`处理后的${this.currentCity}房源数据:`, this.houseData);
                    
                    // 显示房源标记
                    this.showHouseMarkers();
                    
                    // 生成模拟房源详情数据
                    this.generateMockHouseData();
                    
                    this.loading = false;
                    
                    if (this.houseData.length === 0) {
                        uni.showToast({
                            title: `${this.currentCity}暂无房源数据`,
                            icon: 'none'
                        });
                    } else {
                        uni.showToast({
                            title: `已加载${this.houseData.length}个区域房源`,
                            icon: 'success',
                            duration: 1500
                        });
                    }
                } else {
                    throw new Error(`请求失败，状态码: ${res.statusCode}`);
                }
            } catch (error) {
                console.error(`获取${this.currentCity}房源数据失败:`, error);
                this.loading = false;
                uni.showToast({
                    title: `获取${this.currentCity}房源数据失败`,
                    icon: 'none'
                });
                
                // 使用模拟数据作为备用
                this.useMockHouseData();
            }
        },

        // 使用模拟房源数据
        useMockHouseData() {
            // 为每个城市生成模拟的区域房源数据
            const mockData = [];
            const districtCount = Math.floor(Math.random() * 8) + 5; // 5-12个区域
            
            for (let i = 1; i <= districtCount; i++) {
                const latOffset = (Math.random() - 0.5) * 0.2;
                const lngOffset = (Math.random() - 0.5) * 0.2;
                
                mockData.push({
                    value: `AREA_${i}`,
                    label: `${this.currentCity}区域${i}`,
                    count: Math.floor(Math.random() * 100) + 10,
                    coord: {
                        latitude: this.latitude + latOffset,
                        longitude: this.longitude + lngOffset
                    }
                });
            }
            
            this.houseData = mockData;
            console.log(`使用${this.currentCity}模拟房源数据:`, this.houseData);
            
            // 显示房源标记
            this.showHouseMarkers();
            
            // 生成模拟房源详情数据
            this.generateMockHouseData();
            
            uni.showToast({
                title: `已加载${this.houseData.length}个模拟区域`,
                icon: 'success',
                duration: 1500
            });
        },

        // 生成模拟房源数据
        generateMockHouseData() {
            this.allHousesData = {};
            
            this.houseData.forEach((area, index) => {
                const houses = [];
                const houseCount = area.count || Math.floor(Math.random() * 50) + 10;
                
                for (let i = 1; i <= houseCount; i++) {
                    houses.push({
                        id: `${area.value || area.id}-${i}`,
                        title: `${area.label} ${i}号房源`,
                        desc: `位于${this.currentCity}${area.label}的优质房源，交通便利，生活设施齐全`,
                        price: Math.floor(Math.random() * 5000) + 2000,
                        tags: ['精装修', '近地铁', '拎包入住', '南北通透', '学区房'].slice(0, Math.floor(Math.random() * 3) + 1),
                        img: '/static/house-default.jpg',
                        area: area.label,
                        city: this.currentCity
                    });
                }
                
                this.allHousesData[area.value || area.id] = houses;
            });
            
            console.log(`生成的${this.currentCity}模拟房源数据:`, this.allHousesData);
        },

        // 显示房源标记
        showHouseMarkers() {
            if (!this.houseData || this.houseData.length === 0) {
                console.log(`${this.currentCity}没有房源数据`);
                return;
            }

            // #ifdef H5
            this.showH5HouseMarkers();
            // #endif

            // #ifndef H5
            this.showMiniProgramHouseMarkers();
            // #endif
        },

        // H5地图显示房源标记
        showH5HouseMarkers() {
            // #ifdef H5
            if (!this.h5Map || !window.BMapGL) {
                console.log('H5地图未初始化');
                return;
            }

            const BMapGL = window.BMapGL;

            // 清除之前的覆盖物
            this.h5Overlays.forEach(overlay => {
                this.h5Map.removeOverlay(overlay);
            });
            this.h5Overlays = [];

            // 添加房源标记
            this.houseData.forEach((item, index) => {
                const point = new BMapGL.Point(item.coord.longitude, item.coord.latitude);

                // 创建自定义HTML标记
                const label = new BMapGL.Label('', {
                    position: point,
                    offset: new BMapGL.Size(-40, -40)
                });

                // 设置标签内容和样式
                label.setContent(`
                    <div style="
                        background: rgba(33, 185, 122, 0.85);
                        color: white;
                        padding: 15px 20px;
                        border-radius: 50%;
                        font-size: 14px;
                        font-weight: bold;
                        text-align: center;
                        min-width: 80px;
                        min-height: 80px;
                        display: flex;
                        flex-direction: column;
                        align-items: center;
                        justify-content: center;
                        box-shadow: 0 2px 8px rgba(0,0,0,0.3);
                        cursor: pointer;
                        transition: all 0.3s;
                    " onmouseover="this.style.transform='scale(1.1)'" onmouseout="this.style.transform='scale(1)'">
                        <div style="font-size: 16px; margin-bottom: 3px;">${item.label}</div>
                        <div style="font-size: 13px;">${item.count}套</div>
                    </div>
                `);

                label.setStyle({
                    border: 'none',
                    background: 'transparent'
                });

                // 添加点击事件
                label.addEventListener('click', () => {
                    console.log('点击房源区域:', item);
                    this.showAreaHouseDetail(item);
                });

                this.h5Map.addOverlay(label);
                this.h5Overlays.push(label);
            });

            console.log(`H5 ${this.currentCity}房源标记已添加:`, this.h5Overlays.length);
            // #endif
        },

        // 小程序地图显示房源标记
        showMiniProgramHouseMarkers() {
            // #ifndef H5
            if (!this.houseData || this.houseData.length === 0) {
                console.log('没有房源数据可显示');
                return;
            }

            const markers = this.houseData.map((item, index) => {
                console.log('添加标记:', item.label, item.coord);
                return {
                    id: index + 1000,
                    latitude: parseFloat(item.coord.latitude),
                    longitude: parseFloat(item.coord.longitude),
                    width: 80,
                    height: 80,
                    iconPath: '/static/house-marker.png',
                    alpha: 1,
                    label: {
                        content: item.label + '\n' + (item.count || '0') + '套',
                        color: '#ffffff',
                        fontSize: 12,
                        fontWeight: 'bold',
                        bgColor: '#21b97a',
                        borderRadius: 40,
                        padding: 10,
                        textAlign: 'center'
                    },
                    callout: {
                        content: item.label + ': ' + (item.count || '0') + '套房源\n点击查看详情',
                        color: '#333333',
                        fontSize: 14,
                        borderRadius: 8,
                        bgColor: '#ffffff',
                        padding: 12,
                        display: 'BYCLICK'
                    }
                };
            });

            this.markers = [...this.markers, ...markers];
            console.log('小程序房源标记已添加，总标记数:', this.markers.length);
            // #endif
        },

        // 显示区域房源详情
        showAreaHouseDetail(areaData) {
            this.selectedArea = areaData;
            this.currentPage = 1;
            
            // 获取该区域的房源数据
            const areaKey = areaData.value || areaData.id;
            const allHouses = this.allHousesData[areaKey] || [];
            
            // 分页显示
            this.currentHouses = allHouses.slice(0, this.pageSize);
            this.hasMoreHouses = allHouses.length > this.pageSize;
            
            this.showHouseDetail = true;
            
            console.log('显示房源详情:', areaData, '房源数量:', allHouses.length);
        },

        // 关闭房源详情
        closeHouseDetail() {
            this.showHouseDetail = false;
            this.selectedArea = null;
            this.currentHouses = [];
            this.currentPage = 1;
        },

        // 加载更多房源
        loadMoreHouses() {
            if (!this.selectedArea) return;
            
            const areaKey = this.selectedArea.value || this.selectedArea.id;
            const allHouses = this.allHousesData[areaKey] || [];
            
            this.currentPage++;
            const startIndex = (this.currentPage - 1) * this.pageSize;
            const endIndex = startIndex + this.pageSize;
            
            const moreHouses = allHouses.slice(startIndex, endIndex);
            this.currentHouses = [...this.currentHouses, ...moreHouses];
            
            this.hasMoreHouses = endIndex < allHouses.length;
            
            uni.showToast({
                title: `加载了${moreHouses.length}套房源`,
                icon: 'success',
                duration: 1000
            });
        }
    }
}
</script>

<style scoped>
/* 样式保持不变，与之前相同 */
.map-page {
    width: 100%;
    height: 100vh;
    position: relative;
}

.map {
    width: 100%;
    height: 100%;
}

/* H5地图容器 */
.h5-map-container {
    width: 100%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}

/* 搜索框 */
.search-box {
    position: absolute;
    top: 20rpx;
    left: 30rpx;
    right: 30rpx;
    display: flex;
    background-color: #fff;
    border-radius: 50rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
    overflow: hidden;
    z-index: 100;
}

.search-input {
    flex: 1;
    height: 80rpx;
    padding: 0 30rpx;
    font-size: 28rpx;
}

.search-btn {
    width: 120rpx;
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    background-color: #00B386;
    color: #fff;
    font-size: 28rpx;
}

/* 我的位置按钮 */
.location-btn {
    position: absolute;
    bottom: 100rpx;
    right: 30rpx;
    width: 100rpx;
    height: 100rpx;
    background-color: #fff;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.15);
    z-index: 100;
}

.location-icon {
    font-size: 50rpx;
}

/* 搜索结果面板 */
.result-panel {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    max-height: 60vh;
    background-color: #fff;
    border-radius: 20rpx 20rpx 0 0;
    box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.1);
    z-index: 200;
}

.result-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx 40rpx;
    border-bottom: 1px solid #f0f0f0;
}

.result-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
}

.close-result {
    width: 50rpx;
    height: 50rpx;
    line-height: 50rpx;
    text-align: center;
    font-size: 50rpx;
    color: #999;
}

.result-list {
    max-height: 50vh;
}

.result-item {
    padding: 30rpx 40rpx;
    border-bottom: 1px solid #f0f0f0;
}

.result-name {
    font-size: 32rpx;
    color: #333;
    margin-bottom: 10rpx;
}

.result-address {
    font-size: 26rpx;
    color: #999;
}

/* 当前位置信息 */
.location-info {
    position: absolute;
    bottom: 220rpx;
    left: 30rpx;
    right: 30rpx;
    background-color: rgba(255, 255, 255, 0.95);
    padding: 20rpx 30rpx;
    border-radius: 50rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
    z-index: 100;
}

.location-name {
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
}

/* 房源详情弹窗 */
.house-detail-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1000;
}

.modal-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
}

.modal-content {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    border-radius: 30rpx 30rpx 0 0;
    max-height: 80vh;
    display: flex;
    flex-direction: column;
}

.modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 40rpx;
    border-bottom: 1px solid #f0f0f0;
}

.modal-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
}

.modal-close {
    width: 60rpx;
    height: 60rpx;
    line-height: 60rpx;
    text-align: center;
    font-size: 40rpx;
    color: #999;
}

.modal-body {
    flex: 1;
    max-height: 60vh;
    padding: 0 30rpx;
}

.house-list {
    padding: 30rpx 0;
}

.house-item {
    display: flex;
    margin-bottom: 30rpx;
    padding: 30rpx;
    background-color: #f8f8f8;
    border-radius: 20rpx;
}

.house-image {
    width: 200rpx;
    height: 150rpx;
    border-radius: 10rpx;
    margin-right: 30rpx;
}

.house-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
}

.house-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 10rpx;
}

.house-desc {
    font-size: 26rpx;
    color: #666;
    margin-bottom: 15rpx;
}

.house-tags {
    margin-bottom: 15rpx;
}

.tag {
    display: inline-block;
    padding: 8rpx 16rpx;
    background-color: #e6f7f2;
    color: #00B386;
    font-size: 22rpx;
    border-radius: 8rpx;
    margin-right: 10rpx;
    margin-bottom: 10rpx;
}

.house-price {
    display: flex;
    align-items: baseline;
}

.price {
    font-size: 36rpx;
    font-weight: bold;
    color: #ff6b6b;
    margin-right: 10rpx;
}

.unit {
    font-size: 24rpx;
    color: #999;
}

.load-more {
    padding: 40rpx 0;
    text-align: center;
}

.load-more-btn {
    display: inline-flex;
    align-items: center;
    padding: 20rpx 40rpx;
    background-color: #00B386;
    color: #fff;
    border-radius: 50rpx;
    font-size: 28rpx;
}

.load-icon {
    margin-left: 10rpx;
    font-size: 24rpx;
}

.no-more {
    padding: 40rpx 0;
    text-align: center;
    color: #999;
    font-size: 28rpx;
}

/* 城市选择器 */
.city-selector {
    position: absolute;
    top: 20rpx;
    left: 30rpx;
    z-index: 100;
}

.city-btn {
    display: flex;
    align-items: center;
    padding: 15rpx 30rpx;
    background-color: #fff;
    border-radius: 50rpx;
    box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.1);
}

.city-name {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    margin-right: 10rpx;
}

.city-arrow {
    font-size: 20rpx;
    color: #999;
}

/* 城市选择弹窗 */
.city-selector-modal {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    z-index: 1000;
}

.city-modal-mask {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
}

.city-modal-content {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: #fff;
    border-radius: 30rpx 30rpx 0 0;
    max-height: 70vh;
    display: flex;
    flex-direction: column;
}

.city-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 40rpx;
    border-bottom: 1px solid #f0f0f0;
}

.city-modal-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
}

.city-modal-close {
    width: 60rpx;
    height: 60rpx;
    line-height: 60rpx;
    text-align: center;
    font-size: 40rpx;
    color: #999;
}

.city-modal-body {
    flex: 1;
    max-height: 60vh;
    padding: 0 30rpx;
}

.city-list {
    padding: 30rpx 0;
}

.city-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1px solid #f0f0f0;
}

.city-item.active {
    background-color: #e6f7f2;
}

.city-item-name {
    font-size: 32rpx;
    color: #333;
}

.city-item-check {
    font-size: 32rpx;
    color: #00B386;
    font-weight: bold;
}

/* 加载状态 */
.loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 2000;
}

.loading-content {
    background-color: #fff;
    padding: 40rpx;
    border-radius: 20rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.loading-spinner {
    width: 60rpx;
    height: 60rpx;
    border: 6rpx solid #f3f3f3;
    border-top: 6rpx solid #00B386;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 20rpx;
}

.loading-text {
    font-size: 28rpx;
    color: #333;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}
</style>